<template>
  <div class="tw-circle" id="circle">
    <canvas :id="id" :width="itemSize" :height="itemSize"></canvas>
  </div>
</template>

<script scoped>
export default{
  beforeMount () {
    let screen = window.screen.width
    if (screen <= 1366) {
      this.itemSize = 32
    }
  },
  mounted () {
    let timeCanvas = document.getElementById(this.id)
    this.drawMain(timeCanvas, this.percentInt, '#ffdd89', '#263b7e')
  },
  props: ['percent', 'id'],
  data () {
    return {
      itemSize: 40
    }
  },
  computed: {
    percentInt: function () {
      return parseInt(this.percent)
    }
  },
  methods: {
    drawMain: function (drawingElem, percent, forecolor, bgcolor) {
      /*
       @drawingElem: 绘制对象
       @percent：绘制圆环百分比, 范围[0, 100]
       @forecolor: 绘制圆环的前景色，颜色代码
       @bgcolor: 绘制圆环的背景色，颜色代码
       */
      let context = drawingElem.getContext('2d')
      let centerX = drawingElem.width / 2
      let centerY = drawingElem.height / 2
      let rad = Math.PI * 2 / 100
      let speed = 0

      // 绘制背景圆圈
      function backgroundCircle () {
        context.save()
        context.beginPath()
        // 设置线宽
        context.lineWidth = 8
        let radius = centerX - context.lineWidth
        context.lineCap = 'round'
        context.strokeStyle = bgcolor
        context.arc(centerX, centerY, radius, 0, Math.PI * 2, false)
        context.stroke()
        context.closePath()
        context.restore()
      }

      // 绘制运动圆环
      function foregroundCircle (n) {
        context.save()
        context.strokeStyle = forecolor
        context.lineWidth = 8
        context.lineCap = 'round'
        let radius = centerX - context.lineWidth
        context.beginPath()
        // 用于绘制圆弧context.arc(x坐标，y坐标，半径，起始角度，终止角度，顺时针/逆时针)
        context.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 - n * rad, true)
        context.stroke()
        context.closePath()
        context.restore()
      }

      // 执行动画
      (function drawFrame () {
        if (percent === 0) {
          backgroundCircle()
        }
        if (speed >= percent) return
        window.requestAnimationFrame(drawFrame)
        context.clearRect(0, 0, drawingElem.width, drawingElem.height)
        backgroundCircle()
        foregroundCircle(speed)
        speed += 1
      }())
    }
  }
}
</script>

<style scoped></style>
